import collections


class Solution(object):
    def longestWPI(self, hours):
        d = {}
        now = 0
        max_val = 0
        for index, h in enumerate(hours):
            if h > 8:
                now += 1
            else:
                now -= 1
            if now > 0:
                max_val = max(max_val, index + 1)
            else:
                if now - 1 in d:
                    max_val = max(max_val, index - d[now - 1])
                else:
                    if now not in d:
                        d[now] = index
        return max_val
